package com.lipuwater.agent.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ismartlib.framework.permissions.Permission;
import com.ismartlib.framework.permissions.PermissionsResult;
import com.ismartlib.framework.permissions.ResultCallBack;
import com.ismartlib.ui.photoview.PhotoViewAnimIntent;
import com.ismartlib.ui.photoview.activity.PhotoViewAnimActivity;
import com.ismartlib.ui.photoview.utils.ImageAnimAttribute;
import com.ismartlib.ui.view.image.RoundImageView;
import com.ismartlib.utils.NetUtils;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.http.api.ApiRequestsFile;
import com.lipuwater.agent.http.bean.user.UserInfoBean;
import com.lipuwater.agent.ui.dialog.LoadingDialog;
import com.lipuwater.agent.ui.event.UserInfoEvent;
import com.lipuwater.agent.ui.utils.ExitLoginUtils;
import com.lipuwater.agent.utils.LoaderImage;
import com.lipuwater.agent.utils.onclick.NoDoubleClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import io.realm.Realm;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;
import okhttp3.Call;


public class UserInfoActivity extends BaseLayoutActivity {

    @Bind(R.id.image_head)
    RoundImageView imageHead;
    @Bind(R.id.layout_headportrait)
    LinearLayout layoutHeadportrait;
    @Bind(R.id.text_name)
    TextView textName;
    @Bind(R.id.text_phone)
    TextView textPhone;
    private PhotoPickerIntent photoIntent;
    private NoDoubleClick mNoDoubleClick = new NoDoubleClick();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_user_info);
        initTitle(R.drawable.icon_aleft, "个人信息");
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        textName.setText(userName);
        textPhone.setText(account);
        LoaderImage.onLoadingImage(thumbPath, imageHead, R.drawable.logo);
    }

    @OnClick({R.id.image_head, R.id.layout_headportrait, R.id.layout_nickname, R.id.layout_password, R.id.btn_exit_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_head:
                if (mNoDoubleClick.check()) return;
                if (orginPath == null || orginPath.equals("")) return;
                PhotoViewAnimIntent photoViewIntent = new PhotoViewAnimIntent(UserInfoActivity.this);
                photoViewIntent.setImageUrls(orginPath)
                        .getImageAttribute(imageAttribute);
                photoViewIntent.startActivity(imageHead);
                break;
            case R.id.layout_headportrait:
                if (mNoDoubleClick.check()) return;
                Permission.getInstance(UserInfoActivity.this)
                        .requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .results(new ResultCallBack() {
                            @Override
                            public void result(PermissionsResult result) {
                                if (result.getPermission().equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && result.isGranted()) {
                                    photoIntent = new PhotoPickerIntent(UserInfoActivity.this);
                                    photoIntent.setShowCamera(true);
                                    photoIntent.setTailoring(true);
                                    photoIntent.setPhotoCount(1);
                                    photoIntent.setImageSelect(new PhotoPickerActivity.CallbackHead() {
                                        @Override
                                        public void selectResults(Bitmap bitmap, List<String> selectedPhotos) {
                                            if (bitmap != null) {
                                                imageHead.setImageBitmap(bitmap);
                                                postFile(selectedPhotos.get(0));
                                            }
                                        }
                                    });
                                    startActivity(photoIntent);
                                } else if (result.getPermission().equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    PermissionDialog();
                                }
                                Permission.getInstance(UserInfoActivity.this).unresults();
                            }
                        });
                break;
            case R.id.layout_nickname:
                if (mNoDoubleClick.check()) return;
                Intent intent1 = new Intent(this, EditTextActivity.class);
                intent1.putExtra("title", "名称");
                intent1.putExtra("hint", "请输入您的名称");
                intent1.putExtra("content", textName.getText().toString());
                intent1.putExtra("count", 16);
                intent1.putExtra("resultCode", 101);
                startActivityForResult(intent1, 1);
                break;

            case R.id.layout_password:
                if (mNoDoubleClick.check()) return;
                Intent intent2 = new Intent(this, EditTextActivity.class);
                intent2.putExtra("title", "重置密码");
                intent2.putExtra("hint", "请输入您的密码");
                intent2.putExtra("password", true);
                intent2.putExtra("content", "");
                intent2.putExtra("count", 16);
                intent2.putExtra("resultCode", 102);
                startActivityForResult(intent2, 1);
                break;
            case R.id.btn_exit_login:
                if (mNoDoubleClick.check()) return;
                ExitLoginUtils.getInstance().exit();
                break;
        }
    }

    private void postFile(String filePath) {
        LoadingDialog dialog = new LoadingDialog(this, "上传中");
        ApiRequestsFile.PostFile(this, filePath, dialog, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    try {
                        String photoPath = result.getParams().get("name").toString() + "|" +
                                result.getParams().get("path").toString() + "|" +
                                result.getParams().get("thumb").toString() + "|" +
                                result.getParams().get("size").toString();
                        updateUserInfo(null, null, photoPath);
                    } catch (Exception e) {
                        Toast(getString(R.string.network_fails));
                    }
                } else {
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (!NetUtils.isConnected(UserInfoActivity.this)) {
                    Toast(getString(R.string.network_fails));
                } else {
                    Toast(getString(R.string.service_error));
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case 101:
                    String name = data.getStringExtra("data");
                    if (!name.equals("")) {
                        textName.setText(name);
                        updateUserInfo(name, null, null);
                    }
                    break;
                case 102:
                    String password = data.getStringExtra("data");
                    if (!password.equals("")) {
                        updateUserInfo(null, password, null);
                    }
                    break;
            }
        }
    }

    private void updateUserInfo(final String userName, String password, String photoName) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        if (userName != null && !userName.equals("")) {
            params.put("userName", userName);
        }
        if (password != null && !password.equals("")) {
            params.put("password", password);
        }
        if (photoName != null) {
            params.put("photoName", photoName);
        }
        ApiRequestsBasis.updateUserInfo(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    Toast("更新成功");
                    Map<String, Object> params = (Map<String, Object>) result.getParams().get("userInfo");
                    Realm realm = Realm.getDefaultInstance();
                    UserInfoBean userInfoBean = realm.where(UserInfoBean.class).findFirst();
                    if (userInfoBean != null) {
                        realm.beginTransaction();
                        String name = (String) params.get("username");
                        userInfoBean.setName(name);
                        userInfoBean.setOrginPath((String) params.get("orginPath"));
                        userInfoBean.setThumbPath((String) params.get("thumbPath"));
                        realm.commitTransaction();
                        orginPath = (String) params.get("orginPath");
                        EventBus.getDefault().post(new UserInfoEvent(userInfoBean));
                    }
                    realm.close();
                } else {
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (!NetUtils.isConnected(UserInfoActivity.this)) {
                    Toast(getString(R.string.network_fails));
                } else {
                    Toast(getString(R.string.service_error));
                }
            }
        });
    }

    private ImageAnimAttribute imageAttribute = new ImageAnimAttribute() {
        @Override
        public void ImageAttribute(final ImageView imageView, String imageUrl, final PhotoViewAnimActivity photoViewAnimActivity) {
            ImageLoader.getInstance().displayImage(imageUrl, imageView, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    photoViewAnimActivity.onLoadingStarted();
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    String message = null;
                    switch (failReason.getType()) {
                        case IO_ERROR:
                            message = "下载错误";
                            break;
                        case DECODING_ERROR:
                            message = "图片无法显示";
                            break;
                        case NETWORK_DENIED:
                            message = "网络有问题，无法下载";
                            break;
                        case OUT_OF_MEMORY:
                            message = "图片太大无法显示";
                            break;
                        case UNKNOWN:
                            message = "未知的错误";
                            break;
                    }
                    photoViewAnimActivity.onLoadingFailed(message);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    photoViewAnimActivity.onLoadingComplete();
                }
            });
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (photoIntent != null) {
            photoIntent.unImageCallback();
        }
    }

    public void PermissionDialog() {
        new AlertDialog.Builder(this).
                setTitle("帮助")
                .setMessage("请在设置->应用管理->力浦净水->权限管理->读写手机存储\n避免影响正常功能的使用")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        startActivity(intent);
                    }
                }).setNegativeButton("取消", null).show();
    }

}
